package org.example.demo1.service;


import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.VersionInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.example.demo1.Entity.ClusterInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;



import java.io.IOException;

@Service
@Slf4j
public class ClusterService {
    @Value("${kubeconfig.path:D:\\whu-ops\\src\\main\\resources\\templates\\config}")
    private String kubeconfigPath;

    private Config config;

    @PostConstruct
    public void initializeKubernetesClient() {
        try {
            // 从指定路径读取 kubeconfig 文件
            File kubeConfigFile = new File(kubeconfigPath);
            if (!kubeConfigFile.exists()) {
                log.error("Kubeconfig文件不存在: {}", kubeconfigPath);
                return;
            }

            String kubeConfigContents = new String(Files.readAllBytes(kubeConfigFile.toPath()));
            config = Config.fromKubeconfig(kubeConfigContents);

            // 测试连接
            testConnection();
            log.info("Kubernetes客户端初始化成功，kubeconfig路径: {}", kubeconfigPath);
        } catch (IOException e) {
            log.error("读取kubeconfig文件失败: {}", kubeconfigPath, e);
        } catch (Exception e) {
            log.error("初始化Kubernetes客户端失败", e);
        }
    }

    public boolean isConnected() {
        if (config == null) {
            return false;
        }

        try (KubernetesClient client = new DefaultKubernetesClient(config)) {
            // 简单的连接测试 - 获取命名空间列表
            client.namespaces().list();
            return true;
        } catch (Exception e) {
            log.warn("集群连接检查失败: {}", e.getMessage());
            return false;
        }
    }

    public ClusterInfo getClusterInfo() {
        if (config == null) {
            throw new RuntimeException("Kubernetes客户端未初始化");
        }

        try (KubernetesClient client = new DefaultKubernetesClient(config)) {
            // 获取版本信息
            VersionInfo versionInfo = client.getKubernetesVersion();

            // 获取节点信息
            List<Node> nodes = client.nodes().list().getItems();

            // 获取命名空间信息
            List<Namespace> namespaces = client.namespaces().list().getItems();

            return ClusterInfo.builder()
                    .version(versionInfo.getMajor() + "." + versionInfo.getMinor())
                    .gitVersion(versionInfo.getGitVersion())
                    .nodeCount(nodes.size())
                    .namespaceCount(namespaces.size())
                    .build();
        } catch (KubernetesClientException e) {
            log.error("获取集群信息失败", e);
            throw new RuntimeException("获取集群信息失败: " + e.getMessage());
        }
    }

    private void testConnection() {
        if (config != null) {
            try (KubernetesClient client = new DefaultKubernetesClient(config)) {
                client.namespaces().list();
            }
        }
    }

    public KubernetesClient getClient() {
        if (config == null) {
            throw new RuntimeException("Kubernetes客户端未初始化");
        }
        return new DefaultKubernetesClient(config);
    }
}
